Ext.define('CA.base.ImagesPanel', {
    extend: 'Ext.Panel',
    xtype: 'CA.base.ImagesPanel',

    urlFilter: '',

    uses: [
        'CA.base.Image',
        'CA.base.UploadPanel'
    ],

    initComponent: function(){

       this.store = Ext.create('Ext.data.Store', {
            model: 'CA.base.Image',
            proxy: {
                type: 'ajax',
                url: CA.url('/files/load/' + this.urlFilter),
                reader: {
                    type: 'json',
                    root: 'data'
                }
            },
            listeners: {
               scope: this,
               update: this.onStoreUpdate
            }
        });

        var config = {
            layout: 'border',
            padding: 5,
            items: [
                {
                    xtype: 'CA.base.UploadPanel',
                    title: 'Загрузка фотографий',
                    urlFilter: this.urlFilter,
                    width: 350,
                    split: true,
                    region: 'west',
                    listeners: {
                        scope: this,
                        filesUploaded: function(){
                            this.store.load();
                        }
                    }
                },
                this.buildView()
            ]
        };


        Ext.apply(this, config);

        this.on('afterrender', this.store.load, this.store);
        this.callParent();
    },

    onStoreUpdate: function(store, r){
        var data = {}, k;

        for(k in r.modified){
            data[k] = r.data[k];
        }

        Files.update(r.internalId, data);
    },

    buildView: function(){
        return {
            xtype: 'panel',
            region: 'center',
            autoScroll: true,
            title: 'Список фотографий',
            tbar: [
                {
                    text: 'По умолчанию',
                    iconCls: 'c-icon-star',
                    disabled: true,
                    itemId: 'btnDefault',
                    scope: this,
                    handler: this.defaultImage
                },
                '-',
                {
                    text: 'Удалить',
                    iconCls: 'c-icon-image_delete',
                    itemId: 'btnRemove',
                    disabled: true,
                    scope: this,
                    handler: this.removeImages
                },
                '->',
                {
                    text: 'Обновить',
                    iconCls: 'c-icon-reload',
                    scope: this,
                    handler: function(){ this.store.load(); }
                }
            ],
            items: {
                xtype: 'dataview',
                itemId: 'dataview',
                multiSelect: true,
                trackOver: true,
                store: this.store,
                overItemCls: 'x-item-over',
                itemSelector: 'div.thumb-wrap',
                emptyText: '<div class="empty-text">Нет изображений</div>',
                tpl: [
                    '<tpl for=".">',
                    '<div class="thumb-wrap">',
                    '<tpl if="favorite"><div class="favorite"></div></tpl>',
                    '<div class="thumb"><img src="' + CA.url('/files/thumbnail/') + '{file_id}" title="{name}"></div>',
                    '<span class="x-editable">{shortName}</span></div>',
                    '</tpl>',
                    '<div class="x-clear"></div>'
                ],
                plugins: [
                    Ext.create('Ext.ux.DataView.DragSelector', {}),
                    Ext.create('Ext.ux.DataView.LabelEditor', { dataIndex: 'name' })
                ],
                prepareData: function(data) {
                    Ext.apply(data, {
                        shortName: Ext.util.Format.ellipsis(data.name, 15)
                    });

                    return data;
                },
                listeners: {
                    scope: this,
                    selectionchange: this.onSelectionChange
                }
            }
        };
    },

    onSelectionChange: function(view){
        var recs = view.selected.items,
            count = recs.length,
            btnRemove = this.down('#btnRemove'),
            btnDefault = this.down('#btnDefault');

        btnRemove.setDisabled(!count);
        btnDefault.setDisabled(count != 1);
    },

    getSelectedItems: function(){
        var view = this.down('#dataview').selModel;

        return view.selected.items;
    },

    removeImages: function(){
        Ext.Msg.show({
            title: 'Подтверждение',
            msg: 'Удалить выделеные фотографии?',
            buttons: Ext.MessageBox.OKCANCEL,
            icon: Ext.MessageBox.WARNING,
            fn: function (btn) {
                if (btn == 'ok') {
                    var ids = Ext.pluck(this.getSelectedItems(), 'internalId');

                    Files.remove(ids, function(resp){
                        if(resp.success){
                            this.store.load();
                        }
                    }, this);
                }
            },
            scope: this
        });
    },

    defaultImage: function(){
        var rec = this.getSelectedItems()[0],
            pid = rec.data.parent_id,
            ptype = rec.data.parent_type;

        Files.favorite(ptype, pid, rec.internalId, function(resp){
            if(resp.success){
                this.store.load();
            }
        }, this);
    }
});